'use client'

import { useState, useEffect, useCallback } from 'react'
import { useRouter } from 'next/navigation'

interface ClipboardItem {
  id: string
  content: string
  device_id: string
  timestamp: number
}

export default function Dashboard() {
  const [items, setItems] = useState<ClipboardItem[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [showConfirmDialog, setShowConfirmDialog] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [totalItems, setTotalItems] = useState(0)
  const [newMessage, setNewMessage] = useState('')
  const pageSize = 20
  const router = useRouter()

  const fetchHistory = useCallback(async (page: number = 1) => {
    try {
      const response = await fetch(`/api/clipboard/history?page=${page}&page_size=${pageSize}`)
      if (response.ok) {
        const data = await response.json()
        setItems(data.items)
        setTotalPages(data.total_pages)
        setTotalItems(data.total)
        setCurrentPage(data.page)
      } else if (response.status === 401) {
        router.push('/')
      } else {
        setError('获取历史记录失败')
      }
    } catch (err) {
      setError('获取历史记录失败')
    } finally {
      setLoading(false)
    }
  }, [router])

  useEffect(() => {
    fetchHistory(currentPage)
    // 每 5 秒刷新当前页的历史记录
    const interval = setInterval(() => fetchHistory(currentPage), 5000)
    return () => clearInterval(interval)
  }, [fetchHistory, currentPage])

  const handleDelete = async (id: string) => {
    try {
      const response = await fetch(`/api/clipboard/delete/${id}`, {
        method: 'DELETE',
      })
      if (response.ok) {
        setItems(prev => prev.filter(item => item.id !== id))
      } else {
        setError('删除失败')
      }
    } catch (err) {
      setError('删除失败')
    }
  }

  const handleClearAll = async () => {
    try {
      const response = await fetch('/api/clipboard/clear', {
        method: 'DELETE',
      })
      if (response.ok) {
        setItems([])
        setShowConfirmDialog(false)
      } else {
        setError('清除失败')
      }
    } catch (err) {
      setError('清除失败')
    }
  }

  const formatTime = (timestamp: number) => {
    return new Date(timestamp).toLocaleString('zh-CN')
  }

  const handleAddMessage = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newMessage.trim()) return

    try {
      const formData = new FormData()
      formData.append('content', newMessage.trim())

      const response = await fetch('/api/clipboard/sync', {
        method: 'POST',
        body: formData,
      })

      if (response.ok) {
        setNewMessage('')
        // 刷新当前页
        fetchHistory(currentPage)
      } else {
        setError('添加消息失败')
      }
    } catch (err) {
      setError('添加消息失败')
    }
  }

  if (loading) {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <div className="text-lg">加载中...</div>
      </div>
    )
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">剪贴板历史</h1>
          <div className="mt-1 text-sm">
            <span className="text-gray-600">每 5 秒自动刷新 · 共 {totalItems} 条记录</span>
          </div>
        </div>
        <div className="flex items-center space-x-4">
          {items.length > 0 && (
            <button
              onClick={() => setShowConfirmDialog(true)}
              className="rounded-md bg-red-600 px-4 py-2 text-sm font-semibold text-white hover:bg-red-500"
            >
              清除全部
            </button>
          )}
        </div>
      </div>

      {/* 添加消息表单 */}
      <form onSubmit={handleAddMessage} className="mb-8">
        <div className="flex space-x-4">
          <input
            type="text"
            value={newMessage}
            onChange={(e) => setNewMessage(e.target.value)}
            placeholder="输入要同步的内容"
            className="flex-1 rounded-md border-0 py-1.5 px-3 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600"
          />
          <button
            type="submit"
            disabled={!newMessage.trim()}
            className="rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white hover:bg-indigo-500 disabled:opacity-50"
          >
            添加
          </button>
        </div>
      </form>

      {error && (
        <div className="mb-4 rounded-md bg-red-50 p-4 text-red-600">
          {error}
        </div>
      )}

      {showConfirmDialog && (
        <div className="fixed inset-0 z-10 overflow-y-auto">
          <div className="flex min-h-screen items-end justify-center px-4 pb-20 pt-4 text-center sm:block sm:p-0">
            <div className="fixed inset-0 transition-opacity" aria-hidden="true">
              <div className="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            <div className="inline-block transform overflow-hidden rounded-lg bg-white text-left align-bottom shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg sm:align-middle">
              <div className="bg-white px-4 pb-4 pt-5 sm:p-6 sm:pb-4">
                <div className="sm:flex sm:items-start">
                  <div className="mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left">
                    <h3 className="text-lg font-medium leading-6 text-gray-900">
                      确认清除
                    </h3>
                    <div className="mt-2">
                      <p className="text-sm text-gray-500">
                        确定要清除所有历史记录吗？此操作无法撤销。
                      </p>
                    </div>
                  </div>
                </div>
              </div>
              <div className="bg-gray-50 px-4 py-3 sm:flex sm:flex-row-reverse sm:px-6">
                <button
                  type="button"
                  onClick={handleClearAll}
                  className="inline-flex w-full justify-center rounded-md border border-transparent bg-red-600 px-4 py-2 text-base font-medium text-white shadow-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 sm:ml-3 sm:w-auto sm:text-sm"
                >
                  确认清除
                </button>
                <button
                  type="button"
                  onClick={() => setShowConfirmDialog(false)}
                  className="mt-3 inline-flex w-full justify-center rounded-md border border-gray-300 bg-white px-4 py-2 text-base font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 sm:mt-0 sm:w-auto sm:text-sm"
                >
                  取消
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      <div className="space-y-4">
        {items.map((item) => (
          <div
            key={item.id}
            className="rounded-lg bg-white p-4 shadow hover:shadow-md"
          >
            <div className="mb-2 flex items-center justify-between">
              <span className="text-sm text-gray-500">
                {formatTime(item.timestamp)}
              </span>
              <button
                onClick={() => handleDelete(item.id)}
                className="text-sm text-red-600 hover:text-red-800"
              >
                删除
              </button>
            </div>
            <div className="whitespace-pre-wrap break-words">
              {item.content}
            </div>
            <div className="mt-2 text-sm text-gray-500">
              设备: {item.device_id}
            </div>
          </div>
        ))}

        {items.length === 0 && (
          <div className="text-center text-gray-500">
            暂无剪贴板内容
          </div>
        )}
      </div>

      {/* 分页控件 */}
      {totalPages > 1 && (
        <div className="mt-8 flex justify-center space-x-2">
          <button
            onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
            disabled={currentPage === 1}
            className="rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 disabled:opacity-50"
          >
            上一页
          </button>
          <span className="flex items-center px-3 text-sm text-gray-700">
            第 {currentPage} 页，共 {totalPages} 页
          </span>
          <button
            onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
            disabled={currentPage === totalPages}
            className="rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 disabled:opacity-50"
          >
            下一页
          </button>
        </div>
      )}
    </div>
  )
} 